package com.dell.chen.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author ：ChenwithIU
 * @date ：Created in 2020/11/24 9:00
 */
public class JDBCUtils {

    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> conns = new ThreadLocal<>();

    //静态代码块添加配置文件
    static {
        try {
            Properties properties = new Properties();//创建实例

            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");

            //从流中加载数据
            properties.load(inputStream);
            //创建 数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     * 获取数据库连接池中的连接
     * @return 如果返回null,说明获取连接失败<br/>有值就是获取连接成功
     */
    public static Connection getConnection(){
        Connection conn = conns.get();//获取连接

        try {
            if (conn == null){
                conn = dataSource.getConnection();//从数据库连接池中获取连接
                //保存到ThreadLocal对象中，供jdbc操作
                conns.set(conn);

                conn.setAutoCommit(false);//设置手动提交事务
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return conn;
    }

    /**
     * 提交事务，关闭释放连接
     */
    public static void commitAndClose(){
        Connection connection = conns.get();

        if (connection != null){
            try {
                connection.commit();//提交事务
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();//关闭连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //一定要执行remove操作
        conns.remove();
    }


    public static void rollbackAndClose(){
        Connection connection = conns.get();

        if (connection != null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        conns.remove();
    }

}
